import {
  Button,
  Cascader,
  Checkbox,
  Col,
  Input,
  message,
  Modal,
  Radio,
  Row,
  Select,
} from "antd";
import React, {
  FC,
  forwardRef,
  useEffect,
  useImperativeHandle,
  useRef,
  useState,
} from "react";
import "./index.css";
import { fetchRequest } from "@/utils/Request";
import { url } from "@/utils/url";
import { useRequest } from "@umijs/hooks";
import { useHistory } from "react-router";
import { getSecretString } from "@/utils/encrypt";

const { TextArea } = Input;
const { Option } = Select;
const Information: FC = () => {
  const router = useHistory();
  const [deptId, setDeptId] = useState("");
  const [depList, setDepList] = useState<any>([]);
  const [content, setContent] = useState<string>("");
  const [open, setOpen] = useState<boolean>(false);
  const [reviewerUserId, setReviewerUserId] = useState<any>([]);
  const [noticeType, setNoticeType] = useState("1");
  const classValue = useRef<any>(null);
  const acceptValue = useRef<any>(null);

  //学生班级选择成功

  useEffect(() => {
    setContent("");
    classValue.current.clearClass();
    acceptValue.current.clear();
    setDeptId("");
  }, [noticeType]);

  //敏感词信息提醒
  const { run } = useRequest((params) => fetchRequest(url.SENSITIVE, params), {
    manual: true,
    onSuccess: async (result, params) => {
      if (!result.success) {
        message.error(result.errorMsg);
        return;
      } else {
        setOpen(true);
      }
    },
  });

  //敏感词信息提醒
  const { run: Rerun, loading } = useRequest(
    (params) => fetchRequest(url.REVIEWER, params),
    {
      manual: true,
      onSuccess: async (result, params) => {
        if (!result.success) {
          message.error(result.errorMsg);
          return;
        }
        if (result.success) {
          message.success(result.data);
          const id = setTimeout(() => {
            router.go(0);
            clearTimeout(id);
          }, 500);
        }
      },
    }
  );

  const onChange = (value: any) => {
    setDeptId(value[value.length - 1]);
    acceptValue.current.clear();
  };

  const onsubmit = async () => {
    if (!deptId) {
      message.error("请选择班级");
      return;
    }
    if (depList.length === 0) {
      message.error("请选择学生");
      return;
    }
    if (!content) {
      message.error("请填写信息内容");
      return;
    }

    await run({ content });
  };
  const onChangeDep = (depList: any) => {
    setDepList(depList);
  };

  const onOk = async () => {
    await Rerun({
      content,
      deptId,
      noticeType,
      reviewerUserId,
      studentUserId: depList.map((item: any) => getSecretString(`${item}`)),
    });
  };

  const reviewerChange = (value: any) => {
    setReviewerUserId(value);
  };

  const infoType = (value: any) => {
    setNoticeType(value);
  };

  return (
    <div className={"information-wrap"}>
      <Row className={"flex"}>
        <Col span={2}>发布类型:</Col>
        <Col span={20}>
          <InfoType onChange={infoType} />
        </Col>
      </Row>
      <Row className={"flex"}>
        <Col span={2}>学生班级:</Col>
        <Col span={20}>
          <ClassInfo onChange={onChange} ref={classValue} />
        </Col>
      </Row>
      <Row className={"flex"}>
        <Col span={2}>接收人:</Col>
        <Col span={15}>
          <Accept
            deptId={deptId}
            onChangeDep={onChangeDep}
            noticeType={noticeType}
            ref={acceptValue}
          />
        </Col>
      </Row>
      <Row className={"flex"}>
        <Col span={2}>信息内容:</Col>
        <Col span={15}>
          <TextArea
            placeholder="请输入信息内容"
            showCount
            allowClear
            autoSize={{ minRows: 5, maxRows: 5 }}
            maxLength={200}
            onChange={(e) => setContent(e.target.value)}
            value={content}
          />
        </Col>
      </Row>

      <Row className={"flex"}>
        <Col span={2} offset={2}>
          <Button type={"primary"} onClick={onsubmit}>
            提交审核
          </Button>
        </Col>
      </Row>

      <Modal
        title="审核人"
        visible={open}
        onOk={onOk}
        onCancel={() => setOpen(false)}
        okText="提交"
        confirmLoading={loading}
        cancelText="取消"
      >
        <Reviewer onChange={reviewerChange} />
      </Modal>
    </div>
  );
};

const ClassInfo = forwardRef<any, any>(
  ({ onChange, isParentSelect = false }, ref) => {
    const [treeNode, setTreeNode] = useState<any>([]);
    const [classValue, setClassValue] = useState([]);
    const [requestParamTree, setRequestParamTree] = useState<any>({
      level: 0,
      treeId: "0",
    });

    const clearClass = () => {
      setClassValue([]);
    };

    useImperativeHandle(ref, () => ({
      clearClass,
    }));

    const loadData = async (selectedOptions: any) => {
      const targetOption = selectedOptions[selectedOptions.length - 1];
      targetOption.loading = true;

      //组装参数
      const params: any = {
        level: 0,
        treeId: "0",
      };

      selectedOptions.forEach((item: any) => {
        params.treeId = item.treeId;
        params.level = selectedOptions.length;
      });

      console.log(params);
      // console.log(params)

      fetchRequest(url.GET_SCHOOL_ORGANIZATION, params)
        .then((json) => {
          if (json.success) {
            json.data.forEach((item: any) => {
              delete item.children;
            });
            targetOption.children = json.data;
            // console.log(targetOption)
          } else {
            message.error(json.errMsg);
          }
        })
        .catch((error) => {
          console.log(error);
        })
        .finally(() => {
          targetOption.loading = false;
          //主动刷新页面
          setTreeNode([...treeNode]);
        });
    };
    const onChangeClass = (value: any, selectedOptions: any) => {
      const select = value[value.length - 1];
      const flag = selectedOptions.find(
        (item: any) => item.value == select
      )?.isLeaf;

      if (selectedOptions.length === 0) {
        setClassValue([]);
        return;
      }
      if (isParentSelect) {
        setClassValue(value);
        onChange(value);
        return;
      }

      if (flag) {
        setClassValue(() => value);
        onChange(value);
      } else {
        setClassValue([]);
      }
    };

    //请求在校学生组织机构
    async function getSchoolOrganizationRequest(params: any) {
      try {
        const json = await fetchRequest(url.GET_SCHOOL_ORGANIZATION, params);
        if (json.success) {
          message.destroy();
          json.data.forEach((item: any) => {
            delete item.children;
          });
          setTreeNode(json.data);
        } else {
          message.destroy();
          message.error(json.errorMsg);
        }
      } catch (error: any) {
        message.destroy();
        message.error(error.message);
      }
    }

    useEffect(() => {
      getSchoolOrganizationRequest(requestParamTree);
    }, [requestParamTree]);
    return (
      <>
        <Cascader
          placeholder="请选择班级"
          options={treeNode}
          loadData={loadData}
          value={classValue}
          changeOnSelect
          displayRender={(label) => label[label.length - 1]}
          onChange={onChangeClass}
          style={{ width: 400 }}
        />
      </>
    );
  }
);

const Accept = forwardRef<any, any>(
  ({ deptId, onChangeDep, noticeType }, ref) => {
    const [indeterminate, setIndeterminate] = useState(false);
    const [checkAll, setCheckAll] = useState(false);
    const [checkedList, setCheckedList] = useState<any[]>([]);
    const [subjectList, setSubjectList] = useState<any>([]);
    /*智能学生证全选*/
    const [cardIndeterminate, setCardIndeterminate] = useState(false);
    const [cardCheckAll, setCardCheckAll] = React.useState(false);

    const onCheckAllChange = (e: any) => {
      setCheckedList(
        e.target.checked ? subjectList.map((item: any) => item.userId) : []
      );
      setIndeterminate(false);
      setCheckAll(e.target.checked);
      setCardCheckAll(e.target.checked);
    };

    const onCardCheckAll = (e: any) => {
      const list = subjectList
        ?.filter((item: any) => item.flag === 1)
        .map((item: any) => item.userId);
      const noList = subjectList
        ?.filter((item: any) => item.flag !== 1)
        .map((item: any) => item.userId);
      const flag = e.target.checked;
      //不是智能学生证
      //1如果
      setCardCheckAll(flag);

      if (checkAll) {
        if (flag) {
          setCheckedList([...subjectList.map((item: any) => item.userId)]);
        } else {
          setCheckedList(checkedList.filter((check) => !list.includes(check)));
        }
      }

      if (!checkAll) {
        if (flag) {
          setCheckedList(list);
        } else {
          setCheckedList(checkedList.filter((check) => !list.includes(check)));
        }
      }
    };

    useEffect(() => {
      console.log(checkedList.length < subjectList.length);
      setIndeterminate(
        !!checkedList.length && checkedList.length < subjectList.length
      );
    }, [checkedList]);

    const onChange = (list: any) => {
      /*所选择科目item 是否有全选*/

      if (noticeType == "2") {
        // @ts-ignore
        setCheckedList([list[list.length - 1]]);
        return;
      }
      setCheckedList(list);

      setCheckAll(list.length === subjectList.length);
      //元数据
      const subList = subjectList
        .filter((item: any) => list.includes(item.userId))
        .filter((item: any) => item.flag === 1);
      const moreList = subjectList?.filter((item: any) => item.flag === 1);
      setCardCheckAll(subList.length === moreList.length);
    };

    const { data, run } = useRequest(
      (params) =>
        fetchRequest(
          url.GET_NOTICE_STUDENT,
          params ?? {
            deptId: "",
          }
        ),
      {
        manual: true,
        onSuccess: async (result, params) => {
          if (!result.success) {
            message.error(result.errorMsg);
            return;
          }
          setSubjectList(() => result?.data);
        },
      }
    );

    useEffect(() => {
      (async () => {
        if (deptId) {
          await run({ deptId });
        }
      })();
    }, [deptId]);

    useEffect(() => {
      onChangeDep(checkedList);
    }, [checkedList.length]);

    const clear = () => {
      setCheckedList([]);
      setSubjectList([]);
      setCheckAll(false);
      setCardCheckAll(false);
      setIndeterminate(false);
      setCardIndeterminate(false);
    };
    useImperativeHandle(ref, () => ({
      clear,
    }));

    return (
      <div className={"accept-tab"}>
        {subjectList.length > 0 ? (
          <>
            <Checkbox.Group onChange={onChange} value={checkedList}>
              <Row>
                {subjectList?.map((item: any) => (
                  <Col span={6} key={item.userId}>
                    <Checkbox value={item.userId}>
                      {item.studentName}({item.studentId})
                    </Checkbox>
                  </Col>
                ))}
              </Row>
            </Checkbox.Group>
            {noticeType != "2" ? (
              <div className={"check-all"}>
                <Checkbox
                  indeterminate={indeterminate}
                  onChange={onCheckAllChange}
                  checked={checkAll}
                >
                  <span style={{ color: "#1890ff" }}>全选/取消</span>
                </Checkbox>

                <Checkbox
                  indeterminate={cardIndeterminate}
                  onChange={onCardCheckAll}
                  checked={cardCheckAll}
                >
                  <span style={{ color: "#1890ff" }}>智能学生证</span>
                </Checkbox>
              </div>
            ) : null}
          </>
        ) : null}
      </div>
    );
  }
);

const Reviewer: FC<{ onChange: (value: any) => void }> = ({ onChange }) => {
  //敏感词信息提醒
  const { data } = useRequest(() => fetchRequest(url.GET_REVIEWER, {}), {
    onSuccess: async (result, params) => {
      if (!result.success) {
        message.error(result.errorMsg);
        return;
      }
    },
  });

  return (
    <>
      <Row>
        <Col span={4}>审核人:</Col>
        <Col span={20}>
          <Select style={{ width: "100%" }} mode="multiple" onChange={onChange}>
            {data?.data.map((item: any) => (
              <Option value={item.userId} key={item.userId}>
                {item.reviewerName}
              </Option>
            ))}
          </Select>
        </Col>
      </Row>
    </>
  );
};

const InfoType: FC<{ onChange: (value: any) => void }> = ({ onChange }) => {
  const [value, setValue] = useState(1);
  return (
    <Radio.Group
      onChange={(e) => {
        setValue(e.target.value);
        onChange(e.target.value);
      }}
      value={value}
    >
      <Radio value={1}>校务通知</Radio>
      <Radio value={2}>在校表现</Radio>
      <Radio value={4}>作业布置</Radio>
    </Radio.Group>
  );
};

export default Information;
export { ClassInfo };
